<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">班费管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <template>
      <div style="width: 100%; height: 50px;">

        <i>用户名搜索</i>
        <el-input style="width: 150px;"
            v-model="userNameSearch"
            size="mini"
            placeholder="输入关键字搜索"/>
        <el-button type="primary" icon="el-icon-search" size="small" @click="SelectByName()">搜索</el-button>
      </div>
    </template>
    <el-table :data="tableData" border style="width: 100%"  :default-sort = "{prop: 'id'}">
      <el-table-column prop="id" label="ID" width="40" align="center" sortable></el-table-column>
      <el-table-column prop="username" label="用户名" width="120" align="center" sortable></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="100" align="center" sortable></el-table-column>
      <el-table-column prop="phone" label="手机号码" width="120" align="center" sortable></el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="180" align="center" sortable></el-table-column>
      <el-table-column prop="money" label="余额" width="120" align="center" sortable></el-table-column>
      <el-table-column prop="className" label="班级" width="100px" align="center" sortable
                       :filters="this.ClaasFiltersData"
                       :filter-method="filterHandler">

      </el-table-column>
      <el-table-column prop="roleName" :formatter="questionData" label="角色" header-align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="是否启用" width="80" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="changeEnable(scope.row)"
              v-model="scope.row.enable"
              :disabled="scope.row.id == 1"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#AAAAAA">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle size="mini"
                     :disabled="scope.row.id == 1"
                     @click="handleEdit(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle size="mini"
                     :disabled="scope.row.id == 1"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
      <el-pagination
          background
          layout="prev, pager, next"
          :total="1000">
      </el-pagination>
    </el-table>

<!--    分页信息-->
    <template >
      <div class="block" style="margin-top: 35px">
        <el-pagination background="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40,100]"
            :page-size=this.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
            //total总条数 ,page-size每页条数
        </el-pagination>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      ClassData: [],
      ClaasFiltersData: [],
      userNameSearch:'',
      currentPage:'',
      total:'100',
      page:'1',
      pageSize:'10',
    }
  },
  methods: {

    //分页
    handleSizeChange(val) {
      this.pageSize=val;
      this.loadUserList();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page=val;
      this.loadUserList();
      console.log(`当前页: ${val}`);
    },

    //按用户名搜索
    SelectByName(){
      let url = 'http://localhost:8080/user/getByName?username='+this.userNameSearch;
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        this.tableData = responseBody.data;
      });
    },

    //刷选
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] == value;
    },

    //角色
    questionData(row){
      let arr = []
      row.roleName.forEach((item, index)=>{
        arr.push(item);
      })
      return arr.join('  ， ')
    },

    changeEnable(user) {
      let enableText = ['禁用', '启用'];
      let url = 'http://localhost:8080/user/' + user.id;
      if (user.enable == 1) {
        console.log('将启用户');
          url += '/enable';
      } else {
        console.log('将禁用用户');
        url += '/disable';
      }
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          let message = '将学生【' + user.username + '】的启用状态改为【' + enableText[user.enable] + '】成功！';
          this.$message({
            message: message,
            type: 'success'
          });
        } else {
          this.$message.error(responseBody.message);
        }
        if (responseBody.state == 40400) {
          this.loadUserList();
        }
      });
    },
    //编辑信息
    handleEdit(user) {
      // let message = '您正在尝试编辑【' + user.id + '-' + user.nickname + '】的学生详情，抱歉，该功能尚未实现……';
      // this.$alert(message, '提示', {
      //   confirmButtonText: '确定'
      // });
      location.href='/user/upData?id='+user.id;
    },
    //删除
    handleDelete(user) {
      let url = 'http://localhost:8080/user/' + user.id + '/delete';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state != 20000) {
          this.$message.error(responseBody.message);
        }
        if (responseBody.state == 20000 || responseBody.state == 40400) {
          this.loadUserList();
        }
      });
    },
    openDeleteConfirm(user) {
      let message = '此操作将永久删除【' + user.username + '】学生，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(user);
      }).catch(() => {
      });
    },
    loadUserList() {
      console.log('loadUserList');
      console.log('在localStorage中的JWT数据：' + localStorage.getItem('jwt'));
      let url = 'http://localhost:8080/user/page?page='+this.page+'&pageSize='+this.pageSize;
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        this.tableData = responseBody.data.list;
        this.total=responseBody.data.total;
        console.log("加载用户信息")
        console.log(this.tableData);
      });
    },
    //加载班级信息
    loadClassList(){
      console.log('loadClassList');
      console.log('在localStorage中的JWT数据：' + localStorage.getItem('jwt'));
      let url = 'http://localhost:8080/class';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        this.ClassData = responseBody.data;
        for (let i = 0; i < responseBody.data.length; i++) {
          let temp = {
            value:'',
            text:''
          }
          temp.value = responseBody.data[i].className;
          temp.text = responseBody.data[i].className;
          this.ClaasFiltersData.push(temp);
        }
      });
    }
  },
  mounted() {
    console.log('mounted');
    this.loadUserList();
    this.loadClassList();
  }
}
</script>


